package com.maxd.controller;

import com.google.common.collect.Lists;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.adapter.LoginUserHolder;
import com.maxd.bean.PageRes;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.InstructorInfo;
import com.maxd.model.OrderPartnerInfo;
import com.maxd.respository.InstructorInfoRepository;
import com.maxd.respository.OrderPartnerInfoRepository;
import com.maxd.utils.AdminUtils;
import com.maxd.utils.AssertUtil;
import com.maxd.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/instructorInfo")
@Api(value="教官管理", tags = {"教官管理"})
@Slf4j
public class InstructorInfoController {

    @Autowired
    private InstructorInfoRepository instructorInfoRepository;

    @Autowired
    private OrderPartnerInfoRepository orderPartnerInfoRepository;


    @ApiOperation("新增/修改教官信息")
    @PostMapping("/save")
    public Result<Void> save(@RequestBody @Validated InstructorInfo instructorInfo) {
        AdminUtils.checkLogin();
        if(instructorInfo.getPartnerId() != null) {
            OrderPartnerInfo orderPartnerInfo = orderPartnerInfoRepository.findById(instructorInfo.getPartnerId()).orElse(null);
            AssertUtil.assertTrue(orderPartnerInfo != null && "1".equals(orderPartnerInfo.getStatus()), ExceptionEnum.INSTRUCTOR_NOF);
        }

        if(instructorInfo.getId() != null) {
            instructorInfo.setUpdateTime(new Date());
            instructorInfo.setUpdateBy(LoginUserHolder.getAdminId());
        } else {
            instructorInfo.setCreateBy(LoginUserHolder.getAdminId());
            instructorInfo.setUpdateBy(LoginUserHolder.getAdminId());
        }
        instructorInfoRepository.save(instructorInfo);
        return ResultUtil.success(null);
    }

    @IgnoreSecurity
    @ApiOperation("查询教官信息列表")
    @GetMapping("/list")
    public Result<PageRes<InstructorInfo>> list(@ApiParam("页码，从0页开始") @RequestParam("pageNo") Integer pageNo,
                             @ApiParam("每页记录数量") @RequestParam("pageSize") Integer pageSize,
                             @ApiParam("姓名") @RequestParam(value = "name", required = false) String name) {
        // 分页参数
        Sort.Order order = new Sort.Order(Sort.Direction.ASC, "createTime");
        Pageable pageable = PageRequest.of(pageNo, pageSize, Sort.by(order));
        Specification<InstructorInfo> queryCondition = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNotEmpty(name)) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<InstructorInfo> pageList = instructorInfoRepository.findAll(queryCondition, pageable);
        PageRes<InstructorInfo> pageRes = PageUtils.toPageRes(pageList);
        for (InstructorInfo row : pageRes.getRows()) {
            row.setDetails(null);
        }
        return ResultUtil.success(pageRes);
    }

    @IgnoreSecurity
    @ApiOperation("查询教官详细信息")
    @GetMapping("/detail")
    public Result<InstructorInfo> list(@RequestParam("id") Long id) {
        InstructorInfo instructorInfo = instructorInfoRepository.findById(id).orElse(null);
        return ResultUtil.success(instructorInfo);
    }

}
